﻿using com.ruovea.utilty;
using SqlSugar;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace com.ruovea.gogs.entity
{
    public static class QueryableExtension
    {
        /// <summary>
        /// 读取列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="isOrderBy"></param>
        /// <returns></returns>
        public static async Task<List<T>> ToPageAsync<T>(this ISugarQueryable<T> query, Pagination parm)
        {
            int pageSize = parm.rows, pageIndex = parm.page;
            var page = new List<T>();

            string sord = (string.IsNullOrEmpty(parm.sord) || parm.sord.ToLower() == "asc") ? "asc" : "desc";
            query = query.OrderByIF(parm.sidx.NotNullOrWhiteSpace(), parm.sidx + " " + sord);

            parm.records = await query.CountAsync();
            page = parm.records == 0 ? null : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return page;
        }

        /// <summary>
        /// 读取列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="isOrderBy"></param>
        /// <returns></returns>
        public static List<T> ToPage<T>(this ISugarQueryable<T> query, Pagination parm)
        {
            int pageSize = parm.rows, pageIndex = parm.page;
            var page = new List<T>();
            var totalItems = query.Count();

            string sord = (parm.sord.IsNullOrWhiteSpace() || parm.sord.ToLower() == "asc") ? "asc" : "desc";
            query = query.OrderByIF(parm.sidx.NotNullOrWhiteSpace(), parm.sidx + " " + sord);

            page = query.ToPageList(pageIndex, pageSize, ref totalItems);
            parm.records = totalItems;
            return page;
        }
    }
}
